import os
import dify_helper
import pandas as pd
import argparse
import configparser

def run_dify(row:dict,query:str,dh:dify_helper.DifyHelper):
    paramters = {
        "gender":row["【原文】性别"],
        "age":str(row["【原文】年龄"]),
        "film_show":row["【原文】影像表现"],
        "film_diagnose":row["【原文】影像诊断"]
    }
    print(paramters)
    try:
        answer = dh.send_json_message(paramters,'开始解读')
    except Exception as ex:
        print(ex)
        answer = "解读失败"
    # print(answer)
    return answer

def run_dify_batch(data_excel_path:str,excel_writer:pd.ExcelWriter,dh_arr:list[dict],sheet_name:str):
    data_df = pd.read_excel(data_excel_path,sheet_name=sheet_name)
    for dh in dh_arr:
        data_df[dh['agent_name']] = data_df.apply(lambda x:run_dify(x,"开始解读",dh['dh']),axis=1)
    data_df.to_excel(excel_writer,sheet_name,index=False)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="dify批量运行器")
    parser.add_argument('-rep',"--raw_excel_path", type = str, help = "原始excel文件地址")
    # parser.add_argument('-oep',"--out_excel_path", type = str, help = "输出excel文件地址")
    args = parser.parse_args()
    config = configparser.ConfigParser()
    config.read("config.ini")
    print(config.sections())
    raw_excel_path = args.raw_excel_path
    # out_excel_path = args.out_excel_path
    dh_0428 = dify_helper.DifyHelper(config['dify']['base_url'],'app-Oku8OeAdIz9ZG8dSTyQb69gb')
    dh_0919 = dify_helper.DifyHelper(config['dify']['base_url'],'app-OZTv7OOncEnmsGoJx7rUrBHr')
    dh_arr = [{'agent_name':'【模型1】新AI生成结果','dh':dh_0428},{'agent_name':'【模型2】新AI生成结果','dh':dh_0919}]
    writer = pd.ExcelWriter(raw_excel_path,engine="openpyxl", mode='a', if_sheet_exists='overlay')
    sheet_names = ["四肢3条","脊柱7条","胸腹部4条","头部3条","多部位5条","超短2条","超长2条","手术前后3条","检查比较4条"]
    for sheet_name in sheet_names:
        run_dify_batch(raw_excel_path,writer,dh_arr,sheet_name)
    writer.save()
    writer.close()